<template>
  <div class="view-wrapper">
    <div class="head">
      <el-form :model="queryParams" ref="queryForm" :inline="true">
        <el-form-item label="排班日期：" prop="" class="dateClass">
          <el-date-picker v-model="queryParams.date" format="yyyy-MM" value-format="yyyy-MM" type="month"
            placeholder="请选择"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
          <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="listBox" :class="isShowBatch?'listBoxNo':''">
      <div class="listBox_head">
        <div class="listBox_head_top" v-if="isSingleAnchor">
          <span>姓名：{{userInfo.name}}</span>
          <span class="list_dis" >角色：<dict-tag :options="roleTypeLs" :value="userInfo.roleType" /> </span>
          <span>计划直播时长：{{userInfo.planHour}}小时</span>
          <span>实际直播时长：{{userInfo.liveHour}}小时{{userInfo.liveMinute}}分{{userInfo.liveSecond}}秒</span>
        </div>
        <div v-else>
           <el-button type="primary" style="margin: 0 20px 20px 0" @click="viewSchedulingDuration">查看排班时长</el-button>
           <el-button type="primary" style="margin: 10px 0 20px" @click="batchSettings"  v-if="isMonth">批量设置</el-button>
           <!-- <el-button type="primary" style="margin: 10px 0 20px" @click="batchSettings" v-if="isMonth && !isShowBatch">批量设置</el-button> -->
        </div>
       
      </div>
      <el-table v-loading="loading" ref="multipleTable" :data="tabList" stripe border row-key="date"
        @selection-change="handleSelectionChange" tooltip-effect="dark" style="width: 100%">
        <el-table-column type="selection" :reserve-selection="true" width="55" align="center" fixed="left"
          :selectable="selected" v-if="!isSingleAnchor"/>
        <el-table-column label="日期" align="center" prop="date" width="120"></el-table-column>
        <el-table-column label="星期" align="center" prop="weekName" width="120"></el-table-column>
        <el-table-column label="排班" align="center">
          <template slot-scope="scope">
            <div>
              <span v-if="scope.row.liveList == 0">-</span>
              <div class="conter" v-else>
                <el-table :data="scope.row.liveList" border :max-height="320" :header-cell-style="{ background: '#f5f7fa' }"  >
                  <el-table-column align="center" prop="liveName" label="直播间名称"></el-table-column>
                  <el-table-column align="center" prop="sessionNo" label="场次" >
                    <template slot-scope="scope">
                      <div>第{{scope.row.sessionNo}}场</div>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" prop="clientName" label="直播时间" >
                    <template slot-scope="scope">
                      <div>{{ scope.row.startTime }}-{{ scope.row.endTime }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" prop="clientName" label="主播" show-overflow-tooltip >
                    <template slot-scope="scope">
                      <div class="ellipsis_one" v-html="scope.row.anchorsName"></div>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" prop="clientName" label="中控" show-overflow-tooltip >
                    <template slot-scope="scope">
                      <div class="ellipsis_one" v-html="scope.row.controlsName"></div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="100" v-if="isMonth">
          <template slot-scope="scope">
            <div>
              <el-button type="text" size="small" @click="editHandle(scope.row)"
                v-if="scope.row.liveList.length > 0">编辑</el-button>
              <el-button type="text" size="small" @click="setUpHandle(scope.row)" v-else>设置</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <DialogEdit v-if="dialogVisible" :dateIdLs="dateIdLs" :pathType="pathType" :visible.sync="dialogVisible"
      @success="_handleSuccess" @clearId="clearId"></DialogEdit>
    <DialogDuration v-if="dialogDuration"  :visible.sync="dialogDuration"></DialogDuration>
  </div>
</template>

<script>
import {
  workforceCalendarList,workforceUserStatisticsDetail,workforceDetail
} from "@/api/customer/scheduleList";
import DialogEdit from "./components/dialogEdit";
import DialogDuration from "./components/dialogDuration";
import { parseTime } from '@/utils/index.js'
import { computed } from "vue";
export default {
  name: "",
  components: {
    DialogEdit,
    DialogDuration
  },
  data() {
    return {
      dialogVisible: false,//
      dialogDuration:false,//直播时长
      pathType: 'add',
      // 遮罩层
      loading: false,
      //表格数据
      tabList: [],
      dateIdLs: [],//选中的id 列表
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        date: '',//排班日期
      },
      userInfo:{},//单个列表用户详情
      isMonth: true, //判断所选时间是否是在当前月 和下一个月之间
      isSingleAnchor: false,//是否单个编辑
      roleTypeLs: [], //角色状态字典
    };
  },
  created() {
    this.getDict()
    this.getMonthFunc()
    if (this.$route.query.id) {
      this.queryParams.id = this.$route.query.id
      this.isSingleAnchor = true
      this.getWorkforceUserStatisticsDetail()
    }
    this.isMonth = this.determineTime(this.queryParams.date)
    this.getList();
  },
  computed:{
    isShowBatch(){
      let num = 0
      this.tabList.forEach(res=>{
        if(res.liveList && res.liveList.length > 0){
            num++
        }
      })
      if(this.tabList.length == num){
        return true
      }else{
        return false
      }
    },
  },
  methods: {
    //获取状态字典
    getDict() {
      var dictType = "live_user_role_type";
      this.$getSelectList(dictType)
        .then((res) => {
          this.roleTypeLs = res.result[0].dictList;
        })
    },
    // 查看排班时长
    viewSchedulingDuration(){
      this.dialogDuration = true
    },
    // 获取单个列表用户详情
    getWorkforceUserStatisticsDetail(){
      var data = {
        date:this.queryParams.date,
        id:this.queryParams.id
      }
      workforceUserStatisticsDetail(data).then(res=>{
        this.userInfo = res.result
      })
    },
    // 判断所选时间是否是在当前月 和下一个月之间
    determineTime(date) {
      var today = new Date()
      let currentMonth = today.getMonth()
      let nextMonth = today.getMonth() + 1
      let month = (new Date(date)).getMonth()
      if (month <= nextMonth && month >= currentMonth) {
        // console.log(222)
        return true
      } else {
        // console.log(333)
        return false
      }
    },
    // 获取本月
    getMonthFunc() {
      let month = new Date()
      this.queryParams.date = parseTime(month, '{y}-{m}')
    },
    // 是否可以勾选
    selected(row, index) {
      // console.log('row', row.liveList.length)
      if (row.liveList.length > 0) {
        return false; //不可勾选
      } else {
        return true //可勾选
      }
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.dateIdLs = selection.map(item => item.date)
      // console.log(this.dateIdLs)
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      workforceCalendarList(this.queryParams).then(response => {
        this.tabList = response.result;
          this.tabList.forEach(item => {
            if(item.liveList.length > 0){
              item.liveList.forEach(vo=>{
                for (var key in vo) {
                  if (vo[key] === '') {
                      vo[key] = "-";
                  }
                }
                if(vo.anchors && vo.anchors.length > 0){
                  vo.anchorsName = this.processingData(vo.anchors)
                }else{
                  vo.anchorsName = `<span>-</span>`
                }
                if(vo.controls && vo.controls.length > 0){
                  vo.controlsName = this.processingData(vo.controls)
                }else{
                  vo.controlsName = `<span>-</span>`
                }
              })
              // console.log('item.liveList',item.liveList)
            }

          });

        this.loading = false;
      }).catch(error => {
        this.loading = false;
      });
    },
    // 处理主播 中控数据
    processingData(data){
      // console.log('data888',data)
      let array = []
      // console.log('array',array)
      data.forEach(res=>{
        // console.log('this.isSingleAnchor && this.queryForm.id == res.id',this.isSingleAnchor && this.queryForm.id == res.id)
        if(this.isSingleAnchor && this.queryParams.id == res.id){
          array.push(`<span style='color:red;'>${res.name}</span>`)
        }else{
          array.push(`<span>${res.name}</span>`)
        }
      })
      
      return array.join('、')
    },
    lookHandle(row) {
      this.$router.push({ path: "/customer/workforceManagement/scheduleList/details", query: { id: row.id } });
    },
    // 表单重置
    reset() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getMonthFunc()
      this.handleQuery()
    },
    // 批量设置
    batchSettings() {
      if(this.dateIdLs && this.dateIdLs.length > 0){
        this.pathType = 'add'
        this.dialogVisible = true
      }else{
        this.$message.error('请选择日期')
      }

    },
    // 设置排班
    async setUpHandle(row) {
      this.$refs.multipleTable.clearSelection();
      this.dateIdLs = []
      this.dateIdLs.push(row.date)
      // this.pathType = 'add'
      // this.dialogVisible = true
      if(this.isSingleAnchor){
        let params = {
           date:row.date
        }
        let response = await workforceDetail(params)
        let result = response.result.roomDetailVOS
        if(result && result.length > 0){
          this.pathType = 'edit'
          this.dialogVisible = true
        }else{
          this.pathType = 'add'
          this.dialogVisible = true
        }
      }else{
        this.pathType = 'add'
        this.dialogVisible = true
      }
      
    },
    //编辑
    editHandle(row) {
      this.$refs.multipleTable.clearSelection();
      this.dateIdLs = []
      this.dateIdLs.push(row.date)
      this.dialogVisible = true
      this.pathType = 'edit'
    },
    /** 搜索按钮操作 */
    handleQuery() {
      // console.log('this.queryParams.date',this.queryParams.date)
      if(this.queryParams.date == '' || this.queryParams.date == null){
        this.$message.error('请选择排班日期')
        return 
      }
      this.$refs.multipleTable.clearSelection();
      this.queryParams.pageNum = 1;
      this.isMonth = this.determineTime(this.queryParams.date)
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.reset();
    },
    clearId(){
      this.dateIdLs = []
    },
    _handleSuccess(e) {
      //成功回调
      this.$refs.multipleTable.clearSelection();
      this.clearId()
      if (this.$route.query.id) {
        this.getWorkforceUserStatisticsDetail()
       }
      this.resetQuery()
      this.getList()
    },

  }
};

</script>
<style scoped>
.head {
  box-shadow: 0px 4px 12px 0px rgb(1 41 99 / 6%);
  background-color: #fff;
  border-radius: 8px;
  padding: 20px 20px 0;
}

.listBox {
  box-shadow: 0px 4px 12px 0px rgb(1 41 99 / 6%);
  background-color: #fff;
  border-radius: 8px;
  padding: 20px 20px;
  margin-top: 10px;
}
  /* 
      注意，是在 `el-table` 标签的外层DOM结构上设置 `/deep/` 也就是类名为 `myTable` 的这一层
      然后选中表头容器（el-table__fixed-header-wrapper），里面的复选框内部（el-checkbox__inner）
      设置隐藏 权重设置为最高即可
  */
  .listBoxNo /deep/ .el-table__fixed-header-wrapper .el-checkbox__inner{
     display: none !important;
  }

.listBox_head {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.listBox_head_top {
  padding: 10px 0;
  margin-bottom: 20px;
  display: flex;
  flex-direction: row;
  align-items: center;
}

.listBox_head_top span {
  padding-right: 80px;
}

.img_box {
  width: 100px;
  height: 80px;
  border-radius: 4px;
}

.dateClass /deep/ .el-icon-circle-close {
  color: #878d99
}
.list_dis{
  display: flex;
  flex-direction: row;
}
.ellipsis_one{
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.conter{
    flex: 1;
    overflow: auto;
  }
</style>